﻿using DFGJ.WMS_PDA.WebAPI.CfgFile;
using DFGK.WMS.Common.Result;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Helper;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI;
using DFGK_WMS.WebAPI.Controllers.Result;
using Dm;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;

namespace DFGJ.WMS_PDA.WebAPI.Controllers.PDA
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TInventoryQueryController : ControllerBase
    {
        private readonly ITInventoryQuery tTInventoryQuery;
        private readonly ITStocktakingOrderRepository TStocktakingOrderRepository;
        private readonly HttpClient httpClient;
        private readonly ITLogRepository tLog;
        private readonly IUserRepository userRepository;
        public TInventoryQueryController(ITInventoryQuery tTInventoryQuery,ITStocktakingOrderRepository tStocktakingOrderRepository, HttpClient httpClientFactory, ITLogRepository tLogRepository, IUserRepository userRepository)
        {
            this.tTInventoryQuery = tTInventoryQuery;
            this.TStocktakingOrderRepository = tStocktakingOrderRepository;
            this.httpClient = httpClientFactory;
            this.tLog = tLogRepository;
            this.userRepository = userRepository;
        }

        /// <summary>
        /// 盘点查询
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventoryQuery(string PalletBarcode, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400","分页条件有误"));
            }
            var list = tTInventoryQuery.GetInventoryQuery(out var totalCount, PalletBarcode, pageIndex, pageSize);

            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500", 0));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200", totalCount));
        }


        /// <summary>
        /// 根据盘点计划ID查询盘点计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTStocktakingPlanById(long id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "请求参数有误"));
            }
            var list = tTInventoryQuery.GetTStocktakingPlanById(id);

            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// 根据存放库位带出库区物资数量
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventoryNumByAreaId(int areaId)
        {
            if (areaId <= 0)
            {
                return Ok(BaseResult.Result("400", "请求参数有误"));
            }
            var list = tTInventoryQuery.GetInventoryNumByAreaId(areaId);

            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        // 添加库存数量，与盘点数量做差异比较
        //TODO 需要在库存表中增加字段，是否存在差异，默认为false，如果库存数量和盘点数量不一致，则改为true

        /// <summary>
        /// 盘点列表计划查询（海宁）
        /// </summary>
        /// <param name="inventories"></param>
        /// <param name="planid"></param>
        /// <param name="pagenumber"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(LogActionFilter))]
        public IActionResult GetTInventorywuliao([FromBody]PandianDanhaodto dto)
        {
            ApiBaseResult baseResult = new ApiBaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.Code = "400";
                baseResult.Success = false;
                baseResult.Message = "传过来数据格式不正确";
                return Ok(baseResult);
            }
            string message;
            try
            {
                bool pandian = tTInventoryQuery.GetTInventorywuliao(dto.Items, dto.planId, dto.planNumber,out message,out List<TLog> logs);
                if (logs.Count>0)
                {
                    foreach (var item in logs)
                    {
                        tLog.Add(item);
                    }
                }
          
                if (!pandian)
                {
                    baseResult.Code = "400";
                    baseResult.Success = false;
                    baseResult.Message = message;
                    return Ok(baseResult);
                }
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message = "正确";
                return new JsonResult(baseResult);
            }
            catch (Exception ex)
            {

                tLog.Add(new TLog()
                {
                    ActionType = 0,
                    CreateDate = DateTime.Now,
                    Description = ex.Message,
                    LogType = 1,
                });
                return Ok(BaseResult.Result("500", ex.Message));
            }
           }
        /// <summary>
        /// 查询全部盘点pda上信息
        /// </summary>
        /// <param name="planid"></param>
        /// <param name="Ordernum"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPDApandianlist(long? planid,string? Ordernum,int pageindex,int pagesize)
        {
            var list=TStocktakingOrderRepository.GetPDApandianlist(planid, Ordernum, pageindex, pagesize,out var totalt);
            if (list!=null)
            {
                return Ok(BaseResult.Result(list, "200"));
            }
            return Ok(BaseResult.Result("400","错误"));
        }
        /// <summary>
        /// 查询pda上盘点列表数据（海宁）
        /// </summary>
        /// <param name="planid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPDAlistyi() 
        {
            
            var list = TStocktakingOrderRepository.GetPDAlistyi();
            ApiBaseResult baseResult = new ApiBaseResult();
            if (list != null)
            {
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message ="已查询";
                return Ok(BaseResult.Result(list, "200"));
            }
            baseResult.Code = "500";
            baseResult.Success = false;
            baseResult.Message = "查询失败";
            return Ok(baseResult);
        }
        /// <summary>
        /// 根据盘点单号回传状态
        /// </summary>
        /// <param name="ordernum"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult GetXiugaizhuangtai(string ordernum)
        {
            string meessage;
            bool list= tTInventoryQuery.Getpandianxiugai(ordernum, out meessage);
            ApiBaseResult baseResult=new ApiBaseResult();
            if (list)
            {
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message = meessage;
                return Ok(BaseResult.Result(list, "200"));
            }
            baseResult.Code = "500";
            baseResult.Success = false;
            baseResult.Message = meessage;
            return Ok(baseResult);
        }
        //调用接口返回token值
        [HttpGet]
        public async Task<IActionResult> Getyonghuliebiao()
        {
            try
            {
                HttpResponseMessage response = await httpClient.GetAsync("http://192.168.1.60:1988/api/RFID/GetUserList");
                if (response.IsSuccessStatusCode)
                {
                    string resonry = await response.Content.ReadAsStringAsync();//返回数据成功
                    return Ok(resonry);
                }
                else
                {
                    return StatusCode((int)response.StatusCode);//请求失败
                }
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
         
        }
        /// <summary>
        /// 返回所有pda上盘点列表查询
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPdaxianshishuju(int? planid,int pageindex=1,int pagesize=10)
        {
            string meessage;
            int totalCount;
            var items = tTInventoryQuery.GetPdaxianshishuju(planid,pageindex,pagesize,out totalCount);
            ApiItemsResult baseResult = new ApiItemsResult();
            if (items != null)
            {
                baseResult.code = "200";
                baseResult.message = "获取成功!";
                baseResult.items = items;
                baseResult.count = totalCount;
                return Ok(BaseResult.Result(items,"200",totalCount));
            }

            baseResult.code = "500";
            baseResult.items = false;
            baseResult.message = "查询失败";
            return Ok(baseResult);
        }
        /// <summary>
        /// 修改pda盘点人提交
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdatePdaxiugaizhuangtai(PandianDanhaodto dto)
        {
            string uname = HttpContext.User.FindFirstValue("UserName");
            string runame = HttpContext.User.FindFirstValue("RealName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            dto.userid= uid;
            string message;
            bool IsOK = TStocktakingOrderRepository.UpdatePdaxiugaizhuangtai(dto.Items, dto.planId, dto.planNumber, out message,uid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }
        [HttpGet]

        public IActionResult GetUseryonghu(string? uname, int rid=0, int state=3, int pageIndex=1, int pageSize=10)
        {
            int totaclt;
            var resoty = userRepository.GetUserList(uname,  rid,  state,  pageIndex,  pageSize, out int totalCount).Select(n=>new { n.Id,n.UserName,n.RealName});
            ApiBaseResult baseResult = new ApiBaseResult();
            if (resoty!=null)
            {
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message = "查询成功";
                return Ok(BaseResult.Result(resoty, "200"));
            }
            baseResult.Code = "500";
            baseResult.Success = false;
            baseResult.Message = "查询失败";
            return Ok(baseResult);
        }
    }
}
                   